<template>
  <div>
    <div id="showData" style="width: 100%; height: 500px"></div>
    <div id="showPie" style="width: 100%; height: 500px"></div>
    <div id="chartDom" style="width: 100%; height: 500px"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { tcCategory, vMCategory } from '../api/category'
export default {
  created () {
    this.traditionalChineseMedicineTypeData()
    this.westernMedicineData()
  },
  methods: {
    // 发起求
    traditionalChineseMedicineTypeData () {
      tcCategory({
        // headers: {
        //   Authorization: 'Bearer ' + localStorage.getItem('token')
        // }
      }).then(resp => {
        const data = resp.data
        // alert(JSON.stringify(data))
        this.renderBarChart(data)
        this.renderPieChart(data)// 里面的数据不能为空
      }).catch(error => {
        this.handleAxiosError(error)
      })
    },
    westernMedicineData () {
      vMCategory().then(resp => {
        const vMData = resp.data
        this.renderChartDom(vMData)
      }).catch(error => {
        this.handleAxiosError(error)
      })
    },
    handleAxiosError (error) {
      // 检查是否是Axios的网络错误
      if (error.isAxiosError && error.response) {
        console.error('Axios Error:', error.message, 'Status:', error.response.status)
        // 处理您的网络错误，例如显示用户友好的提示
        this.$message.error('网络请求失败，请稍后重试')
      } else {
        // 处理其他类型的错误
        console.error('其他错误:', error.message)
        this.$message.error('网络请求失败，发生错误，请稍后重试')
      }
    },
    // 柱状图
    renderBarChart (data) {
      const option = {
        color: ['#17abd5'],
        title: {
          text: '药物类型数据展示',
          textStyle: {
            color: '#2fe0b2',
            textAlign: 'center' // 设置标题居中对齐
          },
          left: 'center', // 距左
          top: 12 // 距上
        },
        toolbox: {
          feature: {
            saveAsImage: {},
            dataView: {},
            magicType: {
              type: ['bar', 'line']
            }
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          // data: ['职位1', '职位2', '职位3', '职位4', '职位5', '职位6', '职位7', '职位8'] // 替换为您的职位描述
          // 换成服务器返回shuju
          data: data.map(item => item.category).filter(item => item.category == null)
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '数量',
            type: 'bar',
            itemStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: 'red' // 0%处的颜色
                  },
                  {
                    offset: 1,
                    color: 'blue' // 100%处的颜色
                  }
                ]
              }
            },
            markPoint: {
              data: [
                {
                  type: 'max',
                  name: '这是最大值'
                },
                {
                  type: 'min',
                  name: '这是最小值'
                }
              ]
            },
            markLine: {
              data: [
                {
                  type: 'average',
                  name: '这是平均值' // 这个name并不会在页面中显示
                }
              ]
            },
            showBackground: true,
            backgroundStyle: {
              color: 'rgba(180, 180, 180, 0.2)'
            },
            // data: this.generateRandomData(8) // 生成 8 个随机数据
            data: data.map(item => item.categoryCount)
          }
        ]
      }
      const showData = document.getElementById('showData')
      const myChart = echarts.init(showData)
      myChart.setOption(option)
    },
    // 饼图
    renderPieChart (data) {
      const option = {
        title: {
          text: '药物类型数据占比',
          textStyle: {
            color: '#2fe0b2',
            textAlign: 'center' // 设置标题居中对齐
          },
          left: 'center', // 距左
          top: 12 // 距上
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          // data: ['类型1', '类型2', '类型3', '类型4', '类型5'] // 替换为实际类型
          data: data.map(item => item.category) // 替换后端返回的数据类型
        },
        series: [
          {
            name: '物品类型',
            type: 'pie',
            radius: '50%',
            center: ['50%', '60%'],
            data: data.map(item => ({ value: item.categoryCount, name: item.category })), // 替换后端返回的数据类型
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }

      const showPie = document.getElementById('showPie')
      const myChar = echarts.init(showPie)
      myChar.setOption(option)
    },
    renderChartDom (vMData) {
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          data: vMData.map(item => item.category)
        },
        series: [
          {
            name: 'category',
            type: 'pie',
            selectedMode: 'single',
            radius: [0, '30%'],
            label: {
              position: 'inner',
              fontSize: 14
            },
            labelLine: {
              show: false
            },
            data: vMData.map(item => ({ value: item.categoryCount, name: item.category }))
          },
          {
            name: 'category',
            type: 'pie',
            radius: ['45%', '60%'],
            labelLine: {
              length: 30
            },
            label: {
              formatter: '{a|{a}}{abg|}\n{hr|}\n  {b|{b}：}{c}  {per|{d}%}  ',
              backgroundColor: '#F6F8FC',
              borderColor: '#8C8D8E',
              borderWidth: 1,
              borderRadius: 4,
              rich: {
                a: {
                  color: '#6E7079',
                  lineHeight: 22,
                  align: 'center'
                },
                hr: {
                  borderColor: '#8C8D8E',
                  width: '100%',
                  borderWidth: 1,
                  height: 0
                },
                b: {
                  color: '#4C5058',
                  fontSize: 14,
                  fontWeight: 'bold',
                  lineHeight: 33
                },
                per: {
                  color: '#fff',
                  backgroundColor: '#4C5058',
                  padding: [3, 4],
                  borderRadius: 4
                }
              }
            },
            data: vMData.map(item => ({ value: item.categoryCount, name: item.category }))
          }
        ]
      }
      const chartDom = document.getElementById('chartDom')
      const myChart = echarts.init(chartDom)
      myChart.setOption(option)
    }
  }
}
</script>

<style scoped>
#showData {
  margin-top: 13px;
}
#showPie {
  margin-top: 13px;
}
#chartDom {
  margin-top: 13px;
}
</style>
